package com.icoolkj.security.springmvc.controller;

import com.icoolkj.security.springmvc.dto.AuthenticationDTO;
import com.icoolkj.security.springmvc.service.AuthenticationService;
import com.icoolkj.security.springmvc.vo.UserVO;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/06 22:24
 */
@RestController
public class LoginController {

    @Autowired
    private AuthenticationService authenticationService;

    @RequestMapping(value = "/login", produces = "text/plain;charset=utf-8")
    public String login(AuthenticationDTO authenticationDTO, HttpSession session){
        UserVO userVO = authenticationService.authentication(authenticationDTO);

        // 存入到 session （基于 session 方式实现会话功能）
        session.setAttribute(UserVO.SESSION_USER_KEY, userVO);

        return userVO.getFullname() +" 登录成功";
    }

    // 测试退出
    @RequestMapping(value = "logout", produces = "text/plain;charset=utf-8")
    public String logout(HttpSession session){
        session.invalidate();
        return "退出成功";
    }

    // 测试资源 r1
    @RequestMapping(value = "/r/r1", produces = "text/plain;charset=utf-8")
    public String r1(HttpSession session){
        String fullname = null;
        Object object = session.getAttribute(UserVO.SESSION_USER_KEY);

        if(object == null){
            fullname = "匿名";
        } else {
            UserVO userVO = (UserVO) object;
            fullname = userVO.getFullname();
        }
        return fullname + "访问资源 r1";
    }

    // 测试资源 r2
    @RequestMapping(value = "/r/r2", produces = "text/plain;charset=utf-8")
    public String r2(HttpSession session){
        String fullname = null;
        Object object = session.getAttribute(UserVO.SESSION_USER_KEY);

        if(object == null){
            fullname = "匿名";
        } else {
            UserVO userVO = (UserVO) object;
            fullname = userVO.getFullname();
        }
        return fullname + "访问资源 r2";
    }

}
